package org.richin.io.image.util;

/*  
 * ImageUtil.java  
 *  
 * Created on 2008年1月11日, 上午9:26  
 *  
 */

/**  
 *  
 * @author alajl  
 */

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class ImageUtil2 {
	public static final int TURN_LEFT = 1;
	public static final int TURN_RIGHT = 2;

	/*  
	*获取图片RGB数据，并返回大小为width*height大小的一维数组  
	*/
	public int[] getPixels(Image src) {
		int w = src.getWidth();
		int h = src.getHeight();
		int[] pixels = new int[w * h];
		src.getRGB(pixels, 0, w, 0, 0, w, h);
		return pixels;
	}

	/*  
	*将pixels[]里的数据，生成一张图片，图片宽为w，高为h  
	*/
	public Image drawPixels(int[] pixels, int w, int h) {
		Image image = Image.createRGBImage(pixels, w, h, true);
		pixels = null;
		return image;
	}

	/*  
	*调整图片大小  
	*destW 调整后的宽，destH调整后的高  
	*/
	public Image effect_resizeImage(Image src, int destW, int destH) {
		int srcW = src.getWidth();
		int srcH = src.getHeight();

		int[] destPixels = new int[destW * destH];

		int[] srcPixels = getPixels(src);

		for (int destY = 0; destY < destH; ++destY) {
			for (int destX = 0; destX < destW; ++destX) {
				int srcX = (destX * srcW) / destW;
				int srcY = (destY * srcH) / destH;
				destPixels[destX + destY * destW] = srcPixels[srcX + srcY * srcW];
			}
		}

		return drawPixels(destPixels, destW, destH);
	}

	/*  
	* 图片特旋转  
	*/
	public Image effect_rotate(Image src, int direction) {
		Sprite sprite = new Sprite(src);
		switch (direction) {
		case 1:
			sprite.setTransform(Sprite.TRANS_ROT270);
			break;
		case 2:
			sprite.setTransform(Sprite.TRANS_ROT90);
			break;
		}

		Image temp = Image.createImage(src.getHeight(), src.getWidth());
		Graphics g = temp.getGraphics();
		sprite.setPosition(0, 0);
		sprite.paint(g);
		return temp;
	}

}
